package com.zz.wechat.util;

import lombok.Data;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
public class WeChatPayOrderDTO {
    String appid;
    String mch_id;
    String openid;
    String nonce_str;
    String sign;
    String sign_type = "MD5";
    String body;
    String out_trade_no;
    String fee_type = "CNY";
    String total_fee;
    String spbill_create_ip;
    String notify_url;
    String trade_type = "JSAPI";
    String limit_pay = "no_credit";



    String detail;
    String attach;
    String time_start; //yyyyMMddHHmmss 20091225091010
    String time_expire;
    String goods_tag;
    String product_id;
    String device_info;

    public List<String> generateSignatureString() {
        List<String> listStr = new ArrayList<>();
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                String key = field.getName();
                Object value = field.get(this);
                if (!StringUtils.isEmpty(value)) {
                    listStr.add(key + "=" + value.toString());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return listStr;
    }

    public String generateXMLString() {
        StringBuffer listStr = new StringBuffer("<xml>\n");
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                String key = field.getName();
                Object value = field.get(this);
                if (!StringUtils.isEmpty(value)) {
                    listStr.append("\t<" + key + ">" + value.toString() + "</" + key + ">\n");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        listStr.append("</xml>");
        return listStr.toString();
    }

    public static void main(String [] args) {
        WeChatPayOrderDTO dto = new WeChatPayOrderDTO();
        dto.setAppid("1239983812125");
        dto.setMch_id("123109238019821");
        dto.setOpenid("12391203918230asdfajsdqwer");
        dto.setSign(WeiChatUtil.getMD5Signature(dto.generateSignatureString()));
        dto.generateSignatureString();
        System.out.println(dto.generateXMLString());
    }
}
